package com.neuedu.his.framework.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.neuedu.his.entity.Menu;
import com.neuedu.his.entity.User;
import com.neuedu.his.framework.CommonResult;
import com.neuedu.his.service.MenuService;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目：      his
 * 类名:       GrantFilter
 * 创建时间：  2020/12/24  15:56
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
@WebFilter(filterName = "GrantFilter",urlPatterns = "/*")
public class GrantFilter implements Filter {


    private  static Map<Integer ,List> userMenusMap = new HashMap<>();

    MenuService menuService  = new MenuService();
    private static String[] whitelist = {
            "/login",
            "/menu"
    };



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String uri = request.getRequestURI();//          /his/user
        uri = uri.substring(uri.lastIndexOf("/"));   //去掉  his上下文

        String typeUri = uri   ;                       // /user  --> /user?type=query  /user?type=list

        String type = request.getParameter("type");
        if(type!= null && !"".equals(type)){
            typeUri = uri+"?type="+type;
        }


        System.out.println("uri:"+uri);
        //如果是白名单的 执行
        if(inWhiteList(uri)){
            chain.doFilter(req,resp); //放行
        }else{

            HttpSession session = request.getSession();

            User loginUser = (User) session.getAttribute("user");
            if( loginUser != null ){

                //根据用查询，menu 权限,  menu_type = 2
                //查询当前用户的 菜单权限跟当前请求路径是否包含
                //校验是否有权限
                boolean success = true;
                //可以放到缓存中，
//                List<Menu> menuList  = userMenusMap.get(loginUser.getUserId());
//                if(menuList == null){//如果缓存中不存在
//                    menuList = menuService.getUserAllMenus(loginUser.getUserId());
//                    userMenusMap.put(loginUser.getUserId(),menuList);
//                }
//
//                for (Menu menu : menuList) {
//                    if(uri.equals(menu.getUrl()) || typeUri.equals(menu.getUrl())){
//                        success = true;
//                        break;
//                    }
//                }

                if(success){                  //有权限放行
                    chain.doFilter(req,resp);
                }else{
                    //路径无权请求
                    System.out.println("无权请求的路径:【"+uri+"】、【"+typeUri+"】");
                    CommonResult nopromiss = CommonResult.nopromiss("用户无权访问");
                    out(response,nopromiss);
                }
            }else{
                CommonResult nopromiss = CommonResult.nopromiss("未登录的用户,请重新登录");
                out(response,nopromiss);

            }

        }






        //鉴权通过

    }

    @Override
    public void destroy() {

    }

    /**
     * 是否在白名单
     * @param url
     * @return
     */
    public boolean inWhiteList(String url){
        for (String s : whitelist) {
            if(s.equals(url)){
                return true;
            }
        }

        return false;
    }

    public void out(HttpServletResponse response,Object data) throws IOException {
        response.setContentType("application/json");

        String json = JSON.toJSONString(data, SerializerFeature.WriteDateUseDateFormat);
        PrintWriter out = response.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }


}
